import api from '../../api/index';
import { sdk } from '../../config/sdk';
// 在页面中定义激励视频广告
let videoAd = null;

Page({
  data: {
    radio: 1,
    vipIndex: 1,
    loading: true
  },
  onLoad() {
    this.getUserInfo();
    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({ adUnitId: 'adunit-8fb9ff9ef92cc6cd' });
      videoAd.onError((err) => {
        this.$tips({ title: err, duration: 5000 });
      })
      videoAd.onClose((res) => {
        if (!res.isEnded) return this.$error('用户提前关闭');
        const timestamp = 86400000 * 3;
        sdk.request({ url: api.vip, data: { timestamp } }).then(res => {
          if (res.code == 1000) {
            this.$success(res.message);
          }
        })
      })
    }
  },

  // 获取用户信息
  async getUserInfo() {
    const { code, message, data } = await sdk.request({ url: api.getUserInfo, method: 'GET' });
    if (code != 1000) return this.$error(message);
    this.setData({
      userInfo: data,
      loading: false
    });
  },

  vipChange(e) {
    this.setData({
      vipIndex: e.detail.current
    })
  },

  radioChange(e) {
    this.setData({
      radio: parseInt(e.detail)
    })
  },

  showAd() {
    // 用户触发广告后，显示激励视频广告
    if (videoAd) {
      videoAd.show().catch(() => {
        // 失败重试
        videoAd.load()
          .then(() => videoAd.show())
          .catch(err => {
            console.log('激励视频 广告显示失败')
          })
      })
    }
  },

  pay() {
    const info = [{
      body: '一个月会员',
      total: 500
    }, {
      body: '一年会员',
      total: 2000
    }];
    const self = this;
    const radio = self.data.radio;
    sdk.request({
      url: api.wechatPay,
      data: {
        body: info[radio].body,
        total: info[radio].total
      }
    }).then(res => {
      wx.requestPayment({
        ...res.data,
        success(res) {
          self.$success('支付成功');
        },
        fail(err) {
          self.$error('支付失败');
        }
      })
    })
  }
})